package com.frogs.ucenter.openplatform.util;


import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PropertyUtil;
import com.frogs.framework.util.StringUtil;
import com.frogs.ucenter.openplatform.entity.PostObject;
import com.frogs.ucenter.openplatform.util.BaseHttpsConnectUtil.ContentTypeEnum;
import com.frogs.ucenter.v1.util.ApiConstants;

public class SinaWeiboHttpsConnectUtil extends BaseHttpsConnectUtil{
	private final static Logger log = LoggerFactory.getLogger(SinaWeiboHttpsConnectUtil.class);
	
	private static String APPID ;//网站app id
	private static String APPSECRET ;//网站 app key
	private static Integer TIME_OUT ;//超时时间
	private static String propertiesFileName = "sinaweiboopenplatform";
	private static String REDIRECTURI;
	
	// 通过页面授权code 获取access_token
	public final static String OAUTH_ACCESS_TOKEN_URL = "https://api.weibo.com/oauth2/access_token";
	public final static String OAUTH_ACCESS_TOKEN_URL_PARAMS = "client_id=CLIENTID&client_secret=CLIENTSECRET&code=CODE&redirect_uri=REDIRECTURI&grant_type=authorization_code";
	
	// 通过页面授权code 获取access_token
	public final static String OAUTH_OPENID_BY_ACCESS_TOKEN_URL = "https://api.weibo.com/oauth2/get_token_info";
	public final static String OAUTH_OPENID_BY_ACCESS_TOKEN_URL_PARAMS = "access_token=ACCESSTOKEN";
	
	// 通过页面授权code 获取access_token
	public final static String OAUTH_USER_INFO_BY_UID_URL = "https://api.weibo.com/2/users/show.json";
	public final static String OAUTH_USER_INFO_BY_UID_URL_PARAMS = "source=SOURCE&access_token=ACCESSTOKEN&uid=UID";
	
	// 通过refresh token 获取access_token
	public final static String OAUTH_ACCESS_TOKEN_BY_REFRESHTOKEN_URL_PARAMS = "client_id=CLIENTID&client_secret=CLIENTSECRET&refresh_token=REFRESHTOKEN&grant_type=refresh_token";
	
	static{
		APPID = PropertyUtil.getProperty(propertiesFileName, "appId");
		APPSECRET = PropertyUtil.getProperty(propertiesFileName, "appSecret");
		TIME_OUT = PropertyUtil.getIntProperty(propertiesFileName, "timeout" , 20000);
		REDIRECTURI = PropertyUtil.getProperty(propertiesFileName, "redirectUri");
	}
	/**
	 * 说明:通过用户授权码获取access token
	 * @param code 用户授权码
	 * @param redirectUri 重定向地址
	 * @return JSONObject,{ "access_token":"SlAV32hkKG", "remind_in ":3600, "expires_in":3600 }
	 * remind_in即将过期，请使用expires_in，单位为秒
	 */
	public static JSONObject getAccessTokenByCode(String code) {
		PostObject po = new PostObject();
		po.setContent(OAUTH_ACCESS_TOKEN_URL_PARAMS.replace("CLIENTID", APPID).replace("CLIENTSECRET", APPSECRET).replace("CODE", code).replace("REDIRECTURI", REDIRECTURI));
		po.setContentType(ContentTypeEnum.WWW_FORM.toString());
		po.setHeaders(headMap);
		po.setHttps(true);
		po.setUrl(OAUTH_ACCESS_TOKEN_URL);
		po.setTimeOut(TIME_OUT);
		JSONObject jsonObject = post(po);
		return jsonObject;
	}
	
	/**
	 * 说明:通过用户授权码获取access token
	 * @param code 用户授权码
	 * @param redirectUri 重定向地址
	 * @return JSONObject
	 * 返回结果： {
       "uid": 1073880650,//授权用户id
       "appkey": 1352222456,
       "scope": null,
       "create_at": 1352267591,
       "expire_in": 157679471
 }
	 */
	public static JSONObject getOpenidByAccessToken(String accessToken) {
		PostObject po = new PostObject();
		po.setContent(OAUTH_OPENID_BY_ACCESS_TOKEN_URL_PARAMS.replace("ACCESSTOKEN", accessToken));
		po.setContentType(ContentTypeEnum.WWW_FORM.toString());
		po.setHeaders(headMap);
		po.setHttps(true);
		po.setUrl(OAUTH_OPENID_BY_ACCESS_TOKEN_URL);
		po.setTimeOut(TIME_OUT);
		JSONObject jsonObject = get(po);
		return jsonObject;
	}
	
    /**
     * 通过code获取openid
     * @param code 授权code
     * @return {"access_token":"2.00CwWoQBpDjpGCe27c020aded9MvGD","expires_in":"131348","openid":"1164597214"}
     */
    public static JSONObject getOpenid(String code) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	JSONObject json = getAccessTokenByCode(code);
    	if(StringUtil.isEmpty(json.getString("access_token"))){
    		map.put(ApiConstants.RESULT_CODE, ApiConstants.RESULT_FAIL);
    		map.put(ApiConstants.RESULT_DESC, "access_token is null");
    		log.error("获取access_token 有误 json="+json.toString()+" code="+code);
    		json = new JSONObject(map);
    		return json;
    	}
    	map.put(ApiConstants.ACCESS_TOKEN, json.getString("access_token"));
    	map.put(ApiConstants.EXPIRES_IN, json.getString("expires_in"));
    	map.put(ApiConstants.OPEN_ID, json.getString("uid"));
    	map.put(ApiConstants.RESULT_CODE, ApiConstants.RESULT_SUCCESS);
    	json = new JSONObject(map);
        return json;
    }
    
    /**
	 * 说明:通过access token和OPENID获取nickname
	 * @param accessToken 
	 * @return JSONObject
	 * 返回结果： {"ret":0,"nickname":"Peter"}
	 */
	public static JSONObject getNickname(String accessToken,String openId) {
		JSONObject json = null;
		Map<String, Object> map = new HashMap<String, Object>();
    	if(StringUtil.isEmpty(accessToken)){
    		map.put(ApiConstants.RESULT_CODE, ApiConstants.RESULT_FAIL);
    		map.put(ApiConstants.RESULT_DESC, "getNickname access token is null");
    		log.error("获取getNickname有误 accessToken为空");
    		json = new JSONObject(map);
    		return json;
    	}
    	if(StringUtil.isEmpty(openId)){
    		map.put(ApiConstants.RESULT_CODE, ApiConstants.RESULT_FAIL);
    		map.put(ApiConstants.RESULT_DESC, "getNickname openId is null");
    		log.error("获取getNickname有误 openId为空");
    		json = new JSONObject(map);
    		return json;
    	}
		PostObject po = new PostObject();
		po.setContent(OAUTH_USER_INFO_BY_UID_URL_PARAMS.replace("ACCESSTOKEN", accessToken).replace("SOURCE", APPID).replace("UID", openId));
		po.setContentType(ContentTypeEnum.WWW_FORM.toString());
		po.setHeaders(headMap);
		po.setHttps(true);
		po.setUrl(OAUTH_USER_INFO_BY_UID_URL);
		po.setTimeOut(TIME_OUT);
		json = get(po);
		int code = json.getIntValue("ret");
		if(0!=code){
    		map.put(ApiConstants.RESULT_CODE, ApiConstants.RESULT_FAIL);
    		map.put(ApiConstants.RESULT_DESC, "getNickname fail code = "+code);
    		log.error("获取getNickname有误,错误码为code = "+code);
    		json = new JSONObject(map);
    		return json;
		}
		map.put(ApiConstants.RESULT_CODE, ApiConstants.RESULT_SUCCESS);
		map.put(ApiConstants.NICK_NAME, json.getString("screen_name"));
		json = new JSONObject(map);
		return json;
	}
}
